#include "http_server/http_server.hpp"
#include "http_server/http_session.hpp"
#include <iostream>

HttpServer::HttpServer(boost::asio::io_context &io_context, short port)
    : acceptor_(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) // 默认boost::asio::ip::tcp::v4()的IP是0.0.0.0
{
    do_accept();
}

void HttpServer::do_error(const boost::system::error_code& ec)
{
    std::cerr << "Error: " << ec.message() << " (Code: " << ec.value() << ")" << std::endl;
}

void HttpServer::do_accept()
{
    // 异步接收来自客户端的TCP连接（揽客），连接建立后，会自动调用指定的回调函数
    acceptor_.async_accept(
        [this](boost::system::error_code ec, boost::asio::ip::tcp::socket new_socket)
        {
            if (ec)
            {
                do_error(ec);
                return;
            }
            std::make_shared<HttpSession>(std::move(new_socket))->start(); // 建立一次TCP连接会话  传右值，避免拷贝，socket是资源密集型数据
            do_accept();                                                   // 继续异步accept
        });
}
